'use strict';

const { Controller } = require('egg')
const fs = require('mz/fs')
const path = require('path')

class upload extends Controller {
  async upload() {
    const { ctx,service } = this;
    const body = ctx.request.merge({
      row_id:null,
      field_id:null,
    },ctx.request.body)
    const valid = this.app.checkAND([
      { value: body.row_id, type: 'int' },
      {value:body.field_id,type:'int'}
    ]);

    if (!valid) {
      ctx.body = ctx.response.errResult(4001);
      return;
    }

    const date = Date.now();
    const sbNum = Math.random().toString(16).replace('.','');
    const file = ctx.request.files[0];
    const filepath = fs.readFileSync(file.filepath);
    const nameIndex = file.filename.lastIndexOf('.');
    const name = sbNum+date+file.filename.substring(nameIndex);
    fs.writeFileSync(path.join(__dirname, '../../../haiyan/dist/img', name), filepath)

    const data = await service.row.saveImg(body.row_id,body.field_id, `/img/${name}`);
    if (!data) {
      ctx.body = ctx.response.errResult(4001);
      return;
    }
    ctx.body = ctx.response.successResult(2001);

    await fs.unlink(file.filepath);
    ctx.body = body.id;
  }
  
}


module.exports = upload;